package me.ywy.kotlinvideo.ui.fragment

import android.graphics.Color
import android.os.Handler
import android.support.v7.widget.LinearLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.View
import android.widget.LinearLayout
import kotlinx.android.synthetic.main.fragment_home.*
import me.ywy.kotlinvideo.R
import me.ywy.kotlinvideo.adapter.HomeAdapter
import me.ywy.kotlinvideo.base.BaseFragment
import me.ywy.kotlinvideo.presenter.impl.HomePresenter
import me.ywy.kotlinvideo.presenter.interf.IHomePresenter
import me.ywy.kotlinvideo.utils.URLProviderUtils
import me.ywy.kotlinvideo.view.HomeView
import okhttp3.*
import java.io.IOException

/**
 * Created by ywy on 2018-11-02.
 */
class HomeFragment : BaseFragment() , HomeView {
    override fun getDataSuccess() {
        myToast("获取数据成功")
    }

    override fun getDataFalse(msg: String) {
        myToast(msg)
    }

    override fun loadDataSauccess(i: Int) {

        myToast("加载更多")
        mAdapter.loadMore(i)
    }

    val mAdapter by lazy{
        HomeAdapter()
    }
    val mPresenter:IHomePresenter by lazy{
        HomePresenter(this)
    }

    override fun initView(): View? {
        return LayoutInflater.from(context).inflate(R.layout.fragment_home, null)
    }

    override fun initListener() {
        val linearLayoutManager = LinearLayoutManager(context)
        linearLayoutManager.orientation = LinearLayoutManager.VERTICAL
        home_rv.layoutManager = linearLayoutManager
        home_rv.adapter = mAdapter


        refreshlayout.setColorSchemeColors(Color.RED, Color.YELLOW, Color.GREEN)

        refreshlayout.setOnRefreshListener {
            Handler().postDelayed({
                refreshlayout.isRefreshing = false

            }, 2000)
        }

        home_rv.addOnScrollListener(object:RecyclerView.OnScrollListener(){
            override fun onScrollStateChanged(recyclerView: RecyclerView, newState: Int) {
                when(newState){
                    RecyclerView.SCROLL_STATE_IDLE->{
                        var layoutManager = recyclerView.layoutManager;
                        if(layoutManager is LinearLayoutManager){
                            var manager:LinearLayoutManager = layoutManager
                            val lastVisibleItemPosition = manager.findLastVisibleItemPosition()
                            if(lastVisibleItemPosition == recyclerView.adapter.itemCount-1){
                                //正在加载
                                mPresenter.loadMore(3)
                            }
                        }
                    }
                }
            }
        })

    }


    override fun initData() {
        mPresenter.loadDatas()
    }


}